package com.whfc.iot.dust.codec;

import com.whfc.common.util.WindUtil;
import com.whfc.dust.constant.DustConstant;
import com.whfc.dust.entity.DustMsg;
import com.whfc.iot.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class DustMsgDecoder extends MessageToMessageDecoder<ByteBuf> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

        if (!in.isReadable()) {
            return;
        }

        logger.info(in.toString());
        //帧头
        int frameHeader = in.readUnsignedShort();
        if (DustConstant.FRAME_HEADER != frameHeader) {
            logger.info("dust数据帧,帧头错误");
            return;
        }
        //版本号
        int version = in.readUnsignedByte();

        //设备编码
        byte[] deviceCodeBytes = new byte[6];
        in.readBytes(deviceCodeBytes);
        long deviceCode = ByteUtil.low6ByteToLong(deviceCodeBytes);

        //session
        long session = in.readUnsignedInt();

        //cmd
        int cmd = in.readUnsignedByte();

        //数据长度
        int dataLength = in.readUnsignedShort();

        //环境数据
        long pm25 = in.readUnsignedInt();
        long pm10 = in.readUnsignedInt();
        long noise = in.readUnsignedInt();
        int envTemp = in.readInt();
        long envRh = in.readUnsignedInt();
        //风向角度
        long angle = in.readUnsignedInt();
        int windDirection = WindUtil.angle2WindDirection(angle);
        long windSpeed = in.readUnsignedInt();
        long tsp = in.readUnsignedInt();
        long atmos = in.readUnsignedInt();

        //预留值
        int reserved = dataLength - DustConstant.FRAME_CONTENT_LENGTH;
        in.skipBytes(reserved);

        //校验值
        int checkSum = in.readUnsignedByte();

        DustMsg dustMsg = new DustMsg();
        dustMsg.setVersion(version);
        dustMsg.setDataLength(dataLength);
        dustMsg.setDeviceCode(String.valueOf(deviceCode));
        dustMsg.setCmd(cmd);
        dustMsg.setPm25(pm25);
        dustMsg.setPm10(pm10);
        dustMsg.setNoise(noise / 10D);
        dustMsg.setEnvTemp(envTemp / 10D);
        dustMsg.setEnvRh(envRh / 10D);
        dustMsg.setAngle(angle);
        dustMsg.setWindDirection(windDirection);
        dustMsg.setWindSpeed(windSpeed / 10D);
        dustMsg.setTsp(tsp / 100);
        dustMsg.setAtmos(atmos / 10D);
        dustMsg.setCheckSum(checkSum);

        out.add(dustMsg);
    }

}
